package com.yjc.drygoods.authServer.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yjc.common.constant.AuthServerConstant;
import com.yjc.common.exception.BizCodeEnume;
import com.yjc.common.utils.HttpUtils;
import com.yjc.common.utils.R;
import com.yjc.common.vo.MemberRespVo;
import com.yjc.drygoods.authServer.feign.MemberFeignService;
import com.yjc.drygoods.authServer.feign.ThirdPartFeignService;
import com.yjc.drygoods.authServer.vo.SocialVo;
import com.yjc.drygoods.authServer.vo.UserLoginVo;
import com.yjc.drygoods.authServer.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author yjc
 * @create 2022-09-17 11:28
 */
@Slf4j
@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    MemberFeignService memberFeignService;




    /**
     * 退出登录
     */
    @GetMapping("/exit/loginUser")
    public String exitLoginUser(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String id = session.getId();
        log.info("sessionId:{}", id);
        stringRedisTemplate.delete("spring:session:sessions:" + id);
        session.invalidate();
        return "redirect:http://www.drygoods.top";
    }

    /**
     * 微博回调
     *
     * @param code
     * @param session
     * @return
     * @throws Exception
     */
    @GetMapping("/oauth2.0/weibo/success")
    public String oauthLogin(@RequestParam("code") String code, HttpSession session) throws Exception {
        System.out.println("code:" + code);
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "3485455405");
        map.put("client_secret", "0f3a6c7529da5d54ec7c3145de2447e4");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.drygoods.top/oauth2.0/weibo/success");
        map.put("code", code);

        //这里http一定要加s,否则会报超时错误
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), new HashMap<>(), map);
        if (response.getStatusLine().getStatusCode() == 200) {
            String s = EntityUtils.toString(response.getEntity());
            SocialVo socialVo = JSON.parseObject(s, SocialVo.class);

            //远程调用drygoods-member服务，进行会员注册
            R r = memberFeignService.weiboLogin(socialVo);
            if (r.getCode() == 0) {
                //注册成功
                MemberRespVo data = r.getData(new TypeReference<MemberRespVo>() {
                });
                log.info("memberRespVo:{}", data);
                session.setAttribute(AuthServerConstant.LOGIN_USER, data);
                return "redirect:http://www.drygoods.top";
            } else {
                return "redirect:http://auth.drygoods.top/login.html";
            }
        }
        return "redirect:http://auth.drygoods.top/login.html";
    }


    /**
     * 跳转登录页
     */
    @GetMapping("/login.html")
    public String loginIndex(HttpSession session) {

        if (session.getAttribute(AuthServerConstant.LOGIN_USER) != null) {
            return "redirect:http://www.drygoods.top";
        } else {
            return "login";
        }
    }


    /**
     * 获取短信验证码
     *
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {

        //TODO 1.接口防刷

        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(s)) {
            String[] s1 = s.split("_");
            if ((System.currentTimeMillis() - Long.parseLong(s1[1])) < 60000) {
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCodeException(), BizCodeEnume.SMS_CODE_EXCEPTION.getMessageException());
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5);
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);
        //给用户发送短信验证码
        thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }


    /**
     * 登录
     *
     * @param userLoginVo
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/login")
    public String login(@Valid UserLoginVo userLoginVo, BindingResult result, RedirectAttributes redirectAttributes, HttpSession session) {
        //干掉包含"请先登录"信息的session
        String id = session.getId();
        log.info("sessionId:{}", id);
        stringRedisTemplate.delete("spring:session:sessions:" + id);
        if (result.hasErrors()) {
            //密码或账号出错
            List<FieldError> fieldErrors = result.getFieldErrors();
            Map<String, String> errors = fieldErrors.stream().collect(Collectors.toMap(k -> k.getField(), v -> v.getDefaultMessage()));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.drygoods.top/login.html";
        }

        //调用远程服务进行登录
        R r = memberFeignService.login(userLoginVo);
        if (r.getCode() == 0) {
            MemberRespVo data = r.getData(new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://www.drygoods.top";
        } else {
            //登录出错
            Map<String, String> errors = new HashMap<>();
            String msg = r.getData("msg", new TypeReference<String>() {
            });
            errors.put("msg", msg);
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.drygoods.top/login.html";
        }


    }


    /**
     * 注册
     *
     * @param registVo
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo registVo, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            //1.出现异常，返回注册页面
            List<FieldError> fieldErrors = result.getFieldErrors();
            //(v1, v2) -> v1):解决流重名问题
            Map<String, String> errors = fieldErrors.stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage,
                    (v1, v2) -> v1));
            System.out.println(errors);
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.drygoods.top/reg.html";
        }

        String codeRedis = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registVo.getPhone());
        if (!StringUtils.isEmpty(codeRedis)) {
            String code = registVo.getCode();
            if (code.equals(codeRedis.split("_")[0])) {
                //调用远程服务进行注册
                //1.删除redis缓存的验证码
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registVo.getPhone());
                //调用远程服务drygoods-member
                R r = memberFeignService.registMember(registVo);
                if (r.getCode() == 0) {
                    //成功注册，返回登录页面
                    return "redirect:http://auth.drygoods.top/login.html";
                } else {
                    //注册失败
                    Map<String, String> map = new HashMap<>();
                    map.put("msg", r.getData("msg", new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", map);
                    return "redirect:http://auth.drygoods.top/reg.html";
                }
            } else {
                //验证码错误
                Map<String, String> map = new HashMap<>();
                map.put("code", "验证码错误！");
                redirectAttributes.addFlashAttribute("errors", map);
                return "redirect:http://auth.drygoods.top/reg.html";
            }

        } else {
            //redis中没有验证码
            Map<String, String> map = new HashMap<>();
            map.put("code", "验证码错误！");
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.drygoods.top/reg.html";
        }


    }
}
